package com.mini.mybatis.mybatisministep13.executor.statement;

import com.mini.mybatis.mybatisministep13.executor.Executor;
import com.mini.mybatis.mybatisministep13.executor.parameter.ParameterHandler;
import com.mini.mybatis.mybatisministep13.executor.resultset.ResultSetHandler;
import com.mini.mybatis.mybatisministep13.mapping.BoundSql;
import com.mini.mybatis.mybatisministep13.mapping.MappedStatement;
import com.mini.mybatis.mybatisministep13.sqlsession.ResultHandler;
import com.mini.mybatis.mybatisministep13.sqlsession.RowBounds;
import com.mini.mybatis.mybatisministep13.sqlsession.configuration.Configuration;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

public abstract class BaseStatementHandler implements StatementHandler{

    protected Configuration configuration;

    protected Executor executor;

    protected MappedStatement mappedStatement;

    protected Object parameterObject;

    protected ResultSetHandler resultSetHandler;

    protected final ParameterHandler parameterHandler;

    protected final RowBounds rowBounds;
    protected BoundSql boundSql;


    public BaseStatementHandler(Executor executor, MappedStatement mappedStatement, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {
        this.configuration = mappedStatement.getConfiguration();
        this.executor = executor;
        this.mappedStatement = mappedStatement;
        this.rowBounds = rowBounds;

        // 因为update 不会传入boundSql参数，所以需要做初始化处理
        if (boundSql == null){
            boundSql = mappedStatement.getBoundSql(parameterObject);
        }

        this.boundSql = boundSql;
        this.parameterObject = parameterObject;
        this.parameterHandler = configuration.newParameterHandler(mappedStatement,parameterObject,boundSql);
        this.resultSetHandler = configuration.newResultSetHandler(executor,mappedStatement,rowBounds,resultHandler,boundSql);
    }


    @Override
    public Statement prepare(Connection connection) throws SQLException {
        Statement statement = instantiateStatement(connection);
        // 可通过配置文件获取
        statement.setQueryTimeout(350);
        statement.setFetchSize(10000);
        return statement;
    }

    protected abstract Statement instantiateStatement(Connection connection) throws SQLException;

}
